package ro.sergiu.finder.utils;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Toporjinschi
 */
public class NumericDocument extends PlainDocument {

    public static final NumericDocument INTEGER = new NumericDocument(Integer.class);
    public static final NumericDocument FLOAT = new NumericDocument(Float.class);
    public static final NumericDocument LONG = new NumericDocument(Long.class);
    public static final NumericDocument SHORT = new NumericDocument(Short.class);
    public static final NumericDocument BYTE = new NumericDocument(Byte.class);
    public static final NumericDocument DOUBLE = new NumericDocument(Double.class);
    private static final String ALLOW = "0123456789.-+";
    private Class cls = Integer.class;

    public NumericDocument(Class cls) {
        this.cls = cls;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        String text = this.getText(0, this.getLength());
        if (StringUtils.isBlank(str) || !ALLOW.contains(str) || ((str.contains(".") && text.contains(".")))) {
            return;
        }
        if (str.contains(".") && !(cls == Float.class || cls == Double.class)) {
            return;
        }
        if ((str.contains("-") || str.contains("+")) && text.contains("-")) {
            super.remove(0, 1);
        } else if (str.contains("-") && !text.contains("-")) {
            super.insertString(0, str, a);
        } else if (str.contains("+")) {
        } else {
            try {
                checkValue(offs, text, str);
                super.insertString(offs, str, a);
            } catch (NumberFormatException ex) {
            }
        }
    }

    private void checkValue(int offs, String text, String str) {
        String testVal = new StringBuilder(text).insert(offs, str).toString();
        if (cls == Integer.class) {
            Integer.parseInt(testVal);
        } else if (cls == Double.class) {
            Double.parseDouble(testVal);
        } else if (cls == Float.class) {
            Float.parseFloat(testVal);
        } else if (cls == Long.class) {
            Long.parseLong(testVal);
        } else if (cls == Short.class) {
            Short.parseShort(testVal);
        } else if (cls == Byte.class) {
            Byte.parseByte(testVal);
        }
    }

}
